package com.itqf.Util;

import com.itqf.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public  class JwtUtils {
    public static final String SUBJECT = "xdclass";
    public static long EXPIRE = 1000 * 60 * 60 * 24 * 7;//过期时间 毫秒 一周
    public static final String APPSECRET = "xd666";//密钥


    /**
     * 生成jwt
     *
     * @param user
     * @return java.lang.String
     */
     public static String geneJsonWebToken(User user) {
        if (user == null || user.getUserid() == null || user.getUserNickname() == null || user.getUserimg() == null) {
            return null;
        } else {
            String token = Jwts.builder().setSubject(SUBJECT)
                    .claim("id", user.getUserid())
                    .claim("nickname", user.getUserNickname()) //标题
                    .claim("img", user.getUserimg())
                    .setIssuedAt(new Date())    //设置签发时间
                    .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))  //设置终结时间
                    .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();
            return token;
        }
    }

    /**
     * 校验token
     * @param token
     * @return io.jsonwebtoken.Claims
     */
    public static Claims checkToken(String token) {
        try {
            final Claims claims = Jwts.parser().setSigningKey(APPSECRET)
                    .parseClaimsJws(token).getBody();
            return claims;
        }catch (Exception e){
            return null;
        }
    }



/** 
* @Description:  解析token
* @Param: [token] 
* @return: com.itqf.entity.User 
* @Author: 陈岗阳
* @Date: 2019/10/18 
*/ 
    public User TestCheck(String token) {
        Claims claims = JwtUtils.checkToken(token);
        User user=new User();
        if (claims != null) {
            String nickname = (String) claims.get("nickname");
            String img = (String) claims.get("img");
            String id = (String) claims.get("id");
            user.setUserNickname(nickname);
            user.setUserid(id);
            user.setUserimg(img);
            return user;
        } else {
            System.out.println("解密失败非法token");
        }
        return user;
    }


/** 
* @Description: 解析token获得User对象
* @Param: [request] 
* @return: com.itqf.entity.User 
* @Author: 陈岗阳
* @Date: 2019/10/18 
*/ 
    public User Soluecookie(HttpServletRequest request)
    {
         Cookie[] cookies = request.getCookies();

         String cookName="token";

        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(cookName))
            {
                JwtUtils jwtUtils=new JwtUtils();

                User user = jwtUtils.TestCheck(cookie.getValue());

                return user;
            }
        }

        return null;
    }
}



